﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace 软构大作业
{
    
    public partial class Form14 : Form
    {
        private new AutoAdaptWindowsSize AutoSize;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        private DataTable recordTable;    // 当前借阅
        private DataTable historyTable;   // 历史借阅

        // 直接读取全局的当前用户名
        private string CurrentUsername => Global.Instance.CurrentUser.Username;
        // 需要在登录完成后根据 username 查到 user_id 并赋值

        public Form14()
        {
            InitializeComponent();
            ConfigureDataGridView();
            LoadRecordData();
            button1.Click += Button1_Click;
            tabControl1.SelectedIndexChanged += TabControl1_SelectedIndexChanged;
            TabControl1_SelectedIndexChanged(null, null);
            // 设置窗体的KeyPreview属性为true，以便窗体可以接收键盘事件
            this.KeyPreview = true;
            // 为窗体添加KeyDown事件处理
            this.KeyDown += Form14_KeyDown;

        }
        private void ConfigureDataGridView()
        {
            // 设置DataGridView选择模式为整行选择
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 点击单元格时选中整行
            dataGridView1.CellClick += (sender, e) => {
                if (e.RowIndex >= 0)
                {
                    dataGridView1.Rows[e.RowIndex].Selected = true;
                }
            };

            // 允许用户调整列宽
            dataGridView1.AllowUserToResizeColumns = true;
            // 禁用自动调整列宽模式
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
        }
        private void Form14_FormClosed(object sender, FormClosedEventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            Global.Instance.form14login=null;
            Global.Instance.form8login.Show();
        }
        //        private void LoadRecordData()
        //        {
        //            string sql = @"
        //SELECT
        //    r.record_id         AS 记录ID,
        //    b.title             AS 书名,
        //    b.author            AS 作者,
        //    r.borrow_time       AS 借阅日期,
        //    DATEADD(day,14,r.borrow_time) AS 到期日期
        //FROM dbo.BorrowRecords r
        //JOIN library_db.books b   ON r.book_id = b.book_id
        //JOIN library_db.users u   ON r.user_id = u.user_id
        //WHERE u.username    = @uname
        //  AND r.return_time IS NULL
        //ORDER BY r.borrow_time DESC";

        //            // 用 ExecuteQuery 方法，传入一个 SqlParameter 数组
        //            var dt = Data.ExecuteQuery(
        //                sql,
        //                new SqlParameter("@uname", CurrentUsername)
        //            );

        //            dataGridView1.DataSource = dt;
        //            if (dataGridView1.Columns.Contains("记录ID"))
        //                dataGridView1.Columns["记录ID"].Visible = false;
        //            dataGridView1.Columns["书名"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        //            dataGridView1.Columns["作者"].Width = 150;
        //            dataGridView1.Columns["借阅日期"].DefaultCellStyle.Format = "yyyy-MM-dd";
        //            dataGridView1.Columns["到期日期"].DefaultCellStyle.Format = "yyyy-MM-dd";

        //            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        //            dataGridView1.Columns["书名"].FillWeight = 200;
        //            dataGridView1.Columns["作者"].FillWeight = 80;
        //            dataGridView1.Columns["借阅日期"].FillWeight = 60;
        //            dataGridView1.Columns["到期日期"].FillWeight = 60;
        //            dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
        //            dataGridView1.RowTemplate.Height = 40;

        //        }
        private void LoadRecordData()
        {
            string sql = @"
            SELECT
                r.record_id         AS 记录ID,
                b.title             AS 书名,
                b.author            AS 作者,
                r.borrow_time       AS 借阅日期,
                DATEADD(day,14,r.borrow_time) AS 到期日期
            FROM dbo.BorrowRecords r
            JOIN library_db.books b   ON r.book_id   = b.book_id
            JOIN library_db.users u   ON r.user_id   = u.user_id
            WHERE u.username    = @uname
              AND r.return_time IS NULL
            ORDER BY r.borrow_time DESC";


            // 查询到 DataTable
            recordTable = Data.ExecuteQuery(
                sql,
                new SqlParameter("@uname", CurrentUsername)
            );

            // 绑定到网格
            dataGridView1.DataSource = recordTable;
            if (dataGridView1.Columns.Contains("记录ID"))
                dataGridView1.Columns["记录ID"].Visible = false;

            // 列样式略...
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.Columns["书名"].FillWeight = 200;
            dataGridView1.Columns["作者"].FillWeight = 80;
            dataGridView1.Columns["借阅日期"].FillWeight = 60;
            dataGridView1.Columns["到期日期"].FillWeight = 60;
            dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            dataGridView1.RowTemplate.Height = 40;
        }


        private void LoadHistoryData()
        {
            string sql = @"
            SELECT
                r.record_id         AS 记录ID,
                b.title             AS 书名,
                b.author            AS 作者,
                r.borrow_time       AS 借阅日期,
                ISNULL(r.return_time, '9999-12-31') AS 归还日期
            FROM dbo.BorrowRecords r
            JOIN library_db.books b ON r.book_id = b.book_id
            JOIN library_db.users u ON r.user_id = u.user_id
            WHERE u.username = @uname
            ORDER BY r.borrow_time DESC";


            historyTable = Data.ExecuteQuery(
                sql,
                new SqlParameter("@uname", CurrentUsername)
            );

            dataGridView2.DataSource = historyTable;
            if (dataGridView2.Columns.Contains("记录ID"))
                dataGridView2.Columns["记录ID"].Visible = false;

            //dataGridView1.Columns["书名"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            //dataGridView1.Columns["作者"].Width = 150;
            //dataGridView1.Columns["借阅日期"].DefaultCellStyle.Format = "yyyy-MM-dd";
            //dataGridView1.Columns["归还日期"].DefaultCellStyle.Format = "yyyy-MM-dd";
            dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView2.Columns["书名"].FillWeight = 200;
            dataGridView2.Columns["作者"].FillWeight = 80;
            dataGridView2.Columns["借阅日期"].FillWeight = 60;
            dataGridView2.Columns["归还日期"].FillWeight = 60;
            dataGridView2.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            dataGridView2.RowTemplate.Height = 40;
        }


        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选中一条记录。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int recordId = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["记录ID"].Value);

            if (MessageBox.Show("确认归还所选图书？", "归还确认",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                != DialogResult.Yes) return;

            string sql = @"
UPDATE dbo.BorrowRecords
   SET return_time = GETDATE()
 WHERE record_id = @rid
   AND return_time IS NULL";

            int affected = Data.ExecuteNonQuery(
                sql,
                new SqlParameter("@rid", recordId)
            );

            MessageBox.Show(
                affected > 0 ? "归还成功！" : "归还失败：记录不存在或已归还。",
                "归还结果",
                MessageBoxButtons.OK,
                affected > 0 ? MessageBoxIcon.Information : MessageBoxIcon.Warning
            );

            LoadRecordData();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            Global.Instance.form14login.Hide();
            Global.Instance.form8login.Show();
        }


        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
           
        }

        private void Form14_Load(object sender, EventArgs e)
        {
            AutoSize = new AutoAdaptWindowsSize(this);
            this.SizeChanged += new EventHandler(Form_SizeChanged);
        }
        private void Form_SizeChanged(object sender, EventArgs e)
        {//窗体大小改变事件
            if (AutoSize != null) // 一定加这个判断，电脑缩放布局不是100%的时候，会报错
            {
                AutoSize.FormSizeChanged();
            }
        }
        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 切到“历史借阅”页（索引 1）时
            if (tabControl1.SelectedIndex == 1)
            {
               
                //LoadRecordData();
                LoadHistoryData();
            }
            else if(tabControl1.SelectedIndex == 0)// 切回“当前借阅”页
            {
                
                LoadRecordData();
                //LoadHistoryData();

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选中一条记录。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int recordId = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["记录ID"].Value);

            // 检查是否逾期
            string sqlCheck = @"
SELECT CASE WHEN GETDATE() > DATEADD(day,14,borrow_time) THEN 1 ELSE 0 END
  FROM dbo.BorrowRecords
 WHERE record_id = @rid";

            bool isOverdue = Convert.ToInt32(
                Data.ExecuteQuery(sqlCheck, new SqlParameter("@rid", recordId))
                  .Rows[0][0]
            ) == 1;

            if (isOverdue)
            {
                MessageBox.Show("该借阅已逾期，无法续借。", "提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 执行续借：将 borrow_time 更新为当前时间（这样到期日自动延后 14 天）
            string sqlRenew = @"
UPDATE dbo.BorrowRecords
   SET borrow_time = GETDATE()
 WHERE record_id = @rid";

            int affected = Data.ExecuteNonQuery(
                sqlRenew,
                new SqlParameter("@rid", recordId)
            );

            MessageBox.Show(
                affected > 0 ? "续借成功，下次到期日为 14 天后。" : "续借失败，请重试。",
                "续借结果",
                MessageBoxButtons.OK,
                affected > 0 ? MessageBoxIcon.Information : MessageBoxIcon.Error
            );

            LoadRecordData();
        }

 
        private void Button1_Click(object sender, EventArgs e)
        {
            string kw = textBox1.Text.Trim();
           // 决定用哪张表
            DataTable table = tabControl1.SelectedIndex == 1 ? historyTable : recordTable;
            if (table == null) return;

            DataView dv = table.DefaultView;
            if (string.IsNullOrEmpty(kw))
            {
                dv.RowFilter = string.Empty;
            }
            else
            {
                dv.RowFilter = $"书名 LIKE '%{kw}%' OR 作者 LIKE '%{kw}%'";
                // 如果想搜索日期列也加上
                // OR 借阅日期 LIKE '%{kw}%' OR 到期日期 LIKE '%{kw}%' OR 归还日期 LIKE '%{kw}%'
            }

            dataGridView1.DataSource = dv;
            if (dv.Count == 0)
                MessageBox.Show("没有找到匹配的信息", "提示",
                              MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void Form14_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下Enter键
            //if (e.KeyCode == Keys.Enter)
            //{
            //    // 触发button1的点击事件
            //    button1.PerformClick();
            //    // 标记事件已处理，防止其他控件处理该事件
            //    e.Handled = true;
            //    e.SuppressKeyPress = true; // 防止发出"叮"的声音
            //}
        }
        //private void button1_Click_1(object sender, EventArgs e)
        //{
        //    string kw = textBox1.Text.Trim();
        //    // 决定用哪张表
        //    DataTable table = tabControl1.SelectedIndex == 1 ? historyTable : recordTable;
        //    if (table == null) return;

        //    DataView dv = table.DefaultView;
        //    if (string.IsNullOrEmpty(kw))
        //    {
        //        dv.RowFilter = string.Empty;
        //    }
        //    else
        //    {
        //        dv.RowFilter = $"书名 LIKE '%{kw}%' OR 作者 LIKE '%{kw}%'";
        //        // 如果想搜索日期列也加上
        //        // OR 借阅日期 LIKE '%{kw}%' OR 到期日期 LIKE '%{kw}%' OR 归还日期 LIKE '%{kw}%'
        //    }

        //    dataGridView1.DataSource = dv;
        //    if (dv.Count == 0)
        //        MessageBox.Show("没有找到匹配的信息", "提示",
        //                        MessageBoxButtons.OK, MessageBoxIcon.Information);
        //}

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            // 1. 检查当前用户是否有效
            if (Global.Instance.CurrentUser == null || string.IsNullOrEmpty(Global.Instance.CurrentUser.Username))
            {
                MessageBox.Show("用户未登录或会话已过期，请重新登录", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                // 2. 查询当前用户的权限和请求状态
                string checkSql = @"
            SELECT permission, request 
            FROM library_db.users 
            WHERE username = @Username";

                DataTable dt = Data.ExecuteQuery(
                    checkSql,
                    new SqlParameter("@Username", Global.Instance.CurrentUser.Username));

                if (dt.Rows.Count == 0)
                {
                    MessageBox.Show("用户信息不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                bool hasPermission = Convert.ToBoolean(dt.Rows[0]["permission"]);
                string currentRequest = dt.Rows[0]["request"].ToString();

                // 3. 根据权限状态处理
                if (hasPermission)
                {
                    MessageBox.Show("你已经有借阅权限，无需申请",
                                  "提示",
                                  MessageBoxButtons.OK,
                                  MessageBoxIcon.Information);
                }
                else
                {
                    // 4. 检查是否已经提交过申请
                    if (currentRequest == "Yes")
                    {
                        MessageBox.Show("你已经提交过申请，请等待管理员处理",
                                      "提示",
                                      MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);
                        return;
                    }

                    // 5. 更新request为"Yes"
                    string updateSql = @"
                UPDATE library_db.users 
                SET request = 'Yes' 
                WHERE username = @Username";

                    int rowsAffected = Data.ExecuteNonQuery(
                        updateSql,
                        new SqlParameter("@Username", Global.Instance.CurrentUser.Username));

                    if (rowsAffected > 0)
                    {
                        MessageBox.Show("恢复借阅资格申请已提交",
                                      "成功",
                                      MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);

                        // 更新全局变量中的request状态
                        //Global.Instance.CurrentUser.Request = "Yes";
                    }
                    else
                    {
                        MessageBox.Show("申请提交失败，请重试","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败: {ex.Message}","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string kw = textBox2.Text.Trim();
            // 决定用哪张表
            DataTable table = tabControl1.SelectedIndex == 1 ? historyTable : recordTable;
            if (table == null) return;

            DataView dv = table.DefaultView;
            if (string.IsNullOrEmpty(kw))
            {
                dv.RowFilter = string.Empty;
            }
            else
            {
                dv.RowFilter = $"书名 LIKE '%{kw}%' OR 作者 LIKE '%{kw}%'";
                // 如果想搜索日期列也加上
                // OR 借阅日期 LIKE '%{kw}%' OR 到期日期 LIKE '%{kw}%' OR 归还日期 LIKE '%{kw}%'
            }

            dataGridView1.DataSource = dv;
            if (dv.Count == 0)
                MessageBox.Show("没有找到匹配的信息", "提示",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                // 1. 调用按钮的 PerformClick 方法 (推荐，会完整触发按钮的 Click 事件流程)
                button1.PerformClick();

                // 2. 或者直接调用按钮的 Click 事件处理方法 (不推荐，可能绕过一些按钮自身的逻辑)
                // searchButton_Click(searchButton, EventArgs.Empty); // 假设你的 Click 事件处理方法是 searchButton_Click

                // 阻止 Enter 键进一步传播导致发出 "叮" 的声音 (通常在 KeyDown 中需要)
                e.SuppressKeyPress = true; // 告诉系统你已经处理了这个按键，不要再发出默认声音
                                           // 或者 e.Handled = true; (在某些情况下作用类似)
            }
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                // 1. 调用按钮的 PerformClick 方法 (推荐，会完整触发按钮的 Click 事件流程)
                button4.PerformClick();

                // 2. 或者直接调用按钮的 Click 事件处理方法 (不推荐，可能绕过一些按钮自身的逻辑)
                //button4_Click(button4, EventArgs.Empty); // 假设你的 Click 事件处理方法是 searchButton_Click

                // 阻止 Enter 键进一步传播导致发出 "叮" 的声音 (通常在 KeyDown 中需要)
                e.SuppressKeyPress = true; // 告诉系统你已经处理了这个按键，不要再发出默认声音
                                           // 或者 e.Handled = true; (在某些情况下作用类似)
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {

        }

        private void tabPage2_Click(object sender, EventArgs e)
        {

        }
    }
}
